package com.ljx.interceptor;


import com.alibaba.fastjson.JSON;
import com.ljx.Vo.Result;
import com.ljx.util.JwtUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/**
 * @author 22732
 * 自定义一个拦截器
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 防止响应信息乱码问题
        response.setContentType("application/json;charset=utf-8");
         //1.获取请求头中的token
        String token = request.getHeader("token");
        //2.判断token是否为null
        if(StringUtils.hasText(token)){
             //校验token是否合法
             if(JwtUtil.verifyToken(token)){
                  return true;
             }
        }
        PrintWriter writer = response.getWriter();
        Result result=new Result(4001,"未登录");

        String jsonString = JSON.toJSONString(result);
        writer.print(jsonString);
        writer.flush();
        writer.close();
        return false;
    }
}
